package edu.sias.user.service.impl;


import edu.sias.user.component.RedisComponent;
import edu.sias.user.config.AppConfig;
import edu.sias.user.constants.Constants;
import edu.sias.user.entity.dto.SysSettingsDto;
import edu.sias.user.entity.po.EmailCode;
import edu.sias.user.entity.po.UserInfo;
import edu.sias.user.entity.query.EmailCodeQuery;
import edu.sias.user.entity.query.UserInfoQuery;
import edu.sias.user.exception.BusinessException;
import edu.sias.user.mapper.EmailCodeMapper;
import edu.sias.user.service.EmailCodeService;
import edu.sias.user.service.UserInfoService;
import edu.sias.user.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;
@Service
public class EmailCodeServiceImpl implements EmailCodeService {
    private static final Logger logger = LoggerFactory.getLogger(EmailCodeServiceImpl.class);
    @Resource
    private EmailCodeMapper<EmailCode, EmailCodeQuery> emailCodeMapper;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
     private AppConfig appConfig;
    @Resource
    private RedisComponent redisComponent;
    /**
     *  发送邮件验证码
     * @param email
     * @param
     */

    @Override
    public void sendEmailCode(String email) {

            //查询是否有用户
            UserInfo userInfo = userInfoService.getUserInfoByEmail(email);
            if (null!= userInfo  ){
                throw new RuntimeException("邮箱以被绑定");
            }
            String code = StringTools.getRandomNumber(Constants.LENGTH_5);
            //TODO  发送邮件
            sendEmailCode(email, code);

            emailCodeMapper.disableEmailCode(email);
            EmailCode emailCode = new EmailCode();
            emailCode.setCode(code);
            emailCode.setEmail(email);
            emailCode.setStatus(Constants.ZERO);
            emailCode.setCreateTime(new Date());
            emailCodeMapper.insert(emailCode);


    }

    @Override
    public void sendPhoneCode(String phone) {
        //查询是否有用户
        UserInfo userInfo = userInfoService.getUserInfoByPhone(phone);
        if (null!= userInfo  ){
            throw new RuntimeException("手机以被绑定");
        }
        String code = StringTools.getRandomNumber(Constants.LENGTH_5);
        //TODO  发送邮件
       System.out.println("手机号："+phone+"验证码："+code);

        emailCodeMapper.disableEmailCode(phone);
        EmailCode emailCode = new EmailCode();
        emailCode.setCode(code);
        emailCode.setEmail(phone);
        emailCode.setStatus(Constants.ZERO);
        emailCode.setCreateTime(new Date());
        emailCodeMapper.insert(emailCode);
    }

    @Override
    public void checkCode(String email, String code) {
        EmailCode emailCode = emailCodeMapper.selectByEmailAndCode(email, code);
        if (null == emailCode) {
            throw new BusinessException("邮箱验证码不正确");
        }
        if (emailCode.getStatus() == 1 || System.currentTimeMillis() - emailCode.getCreateTime().getTime() > Constants.LENGTH_15 * 1000 * 60) {
            throw new BusinessException("邮箱验证码已失效");
        }
        emailCodeMapper.disableEmailCode(email);
    }



    private void sendEmailCode(String toEmail, String code) {
        try {
            MimeMessage message = javaMailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(message, true);//邮件内容，支持html
            //邮件发件人

            helper.setFrom("1922975323@qq.com");
            //邮件收件人 1或多个
            helper.setTo(toEmail);//收件人

            SysSettingsDto sysSettingsDto = new SysSettingsDto();

            //邮件主题
            helper.setSubject(sysSettingsDto.getRegisterEmailTitle());
            //邮件内容
            helper.setText(String.format(sysSettingsDto.getRegisterEmailContent(), code));
            //String.format(...) 方法，用于格式化字符串。在 EmailCodeServiceImpl.java 中，
            // 该方法的作用是将邮件内容模板中的占位符替换为实际的验证码
            //邮件发送时间
            helper.setSentDate(new Date());
            javaMailSender.send(message);
        } catch (Exception e) {
            logger.error("邮件发送失败", e);
            throw new RuntimeException("邮件发送失败");
        }
    }
}